<?php

namespace app\api\v1\controller;

use app\api\v1\validate\auth\login\WechatAppLoginValidate;
use app\api\v1\validate\order\pay\PayOrderQueryByAppleValidate;
use app\api\v1\validate\order\pay\PayOrderQueryValidate;
use app\api\v1\validate\order\pay\PayVipValidate;
use app\api\v1\validate\order\pay\QueryBillsByAppleValidate;
use app\api\v1\validate\order\pay\ResumePurchaseByAppleValidate;
use app\api\v1\validate\user\user\BindMobileValidate;
use app\api\v1\validate\user\user\ChangeInfoValidate;
use app\api\v1\validate\user\user\ChangePasswordValidate;
use app\api\v1\validate\user\user\RelieveMobileValidate;
use app\common\ApiBase;
use app\common\ApiStatus;
use app\service\AppleService;
use Exception;
use polymerize\order\service\PayModelService;
use polymerize\order\service\PayService;
use polymerize\user\service\UserService;
use support\Request;
use support\Response;

class User extends ApiBase
{
    private int $uid = 0;

    public function beforeAction()
    {
        if (empty(request()->uid)) return $this->apiFailed('请先登录', ApiStatus::API_NEED_LOGIN->value);
        $this->uid = request()->uid;

        parent::beforeAction();
    }


    /**
     * 用户信息
     *
     * @route /api/v1/user/info
     * @return Response
     */
    public function info(): Response
    {
        $info = UserService::getInstance()->getUserInfo($this->uid);

        return $this->apiSuccess($info);
    }

    /**
     * 微信小程序获取手机号
     * /v1/user/wechatAppGetPhone
     *
     * @param Request $request
     * @return Response
     */
    public function wechatAppGetPhone(Request $request): Response
    {
        $validate = new WechatAppLoginValidate();
        if (!$validate->check($request->post())) return $this->apiFailed($validate->getError());

        $code = $request->post('code', '');

        $res = UserService::getInstance()->wechatAppGetPhone($code, $this->uid);

        return ($res['code'] == 200) ? $this->apiSuccess() : $this->apiFailed($res['msg']);
    }

    /**
     * 退出登录
     *
     * @param Request $request
     * @return Response
     */
    public function out(Request $request): Response
    {
        $token = $request->header('Authorization', '');

        $res = UserService::getInstance()->outLogin($this->uid, $token);

        return $res ? $this->apiSuccess() : $this->apiFailed();
    }

    /**
     * 删除注销用户
     *
     * @param Request $request
     * @return Response
     */
    public function cancel(Request $request): Response
    {
        $request->session()->flush();
        $sessionId = $request->session()->getId();

        $res = UserService::getInstance()->cancelUser($this->uid, $sessionId);

        return $res ? $this->apiSuccess() : $this->apiFailed();
    }

    /**
     * 修改用户信息
     *
     * @param Request $request
     * @return Response
     */
    public function changeInfo(Request $request): Response
    {
        $validate = new ChangeInfoValidate();
        if (!$validate->check($request->post())) return $this->apiFailed($validate->getError());

        $type     = $request->post('type', '');
        $avatar   = $request->post('avatar', '');
        $nickname = $request->post('nickname', '');
        $sex      = $request->post('sex', '');
        $birthday = $request->post('birthday', '');

        $res = UserService::getInstance()->changeInfo((int)$this->uid, (string)$type, (string)$avatar, (string)$nickname, (int)$sex, (string)$birthday);

        return $res ? $this->apiSuccess() : $this->apiFailed();
    }

    /**
     * 手机验证码修改密码[发送短信验证]
     *
     * @throws Exception
     */
    public function changePassword(Request $request): Response
    {
        $validate = new ChangePasswordValidate();
        if (!$validate->check($request->post())) return $this->apiFailed($validate->getError());

        $mobile          = $request->post('mobile', '');
        $smsCode         = $request->post('sms_code', '');
        $password        = $request->post('password', '');
        $confirmPassword = $request->post('confirm_password', '');
        if ($password != $confirmPassword) return $this->apiFailed('请输入正确的确认密码');

        $res = UserService::getInstance()->changePassword($this->uid, $mobile, $smsCode, $password);
        if ($res['code'] != 200) return $this->apiFailed($res['msg']);

        return $this->apiSuccess();
    }

    /**
     * VIP支付购买
     *
     * @param Request $request
     * @return Response
     */
    public function payVip(Request $request): Response
    {
        $validate = new PayVipValidate();
        if (!$validate->check($request->post())) return $this->apiFailed($validate->getError());

        $vipType         = $request->post('type', '');
        $payType         = $request->post('pay_type', '0');
        $disposableGoods = $request->post('disposable_goods', 0);

        $res = PayService::getInstance()->payVip($this->uid, $request->os_type, $vipType, $payType, $disposableGoods);

        if ($res['code'] != 200) return $this->apiFailed($res['msg']);
        return $this->apiSuccess($res['data']);
    }

    /**
     * 订单支付结果查询
     * v1/user/payOrderQuery
     *
     * @param Request $request
     * @return Response
     * @throws Exception
     */
    public function payOrderQuery(Request $request): Response
    {
        $validate = new PayOrderQueryValidate();
        if (!$validate->check($request->post())) return $this->apiFailed($validate->getError());

        $orderNo = $request->post('order_no', '');
        $payType = $request->post('pay_type', '');

        $res = PayService::getInstance()->payOrderQuery($orderNo, $payType);

        if ($res['code'] != 200) return $this->apiFailed($res['msg']);
        return $this->apiSuccess($res['data'], $res['msg']);
    }

    /**
     * 绑定手机号
     *
     * @param Request $request
     * @return Response
     */
    public function bindMobile(Request $request): Response
    {
        $validate = new BindMobileValidate();
        if (!$validate->check($request->post())) return $this->apiFailed($validate->getError());

        $mobile  = $request->post('mobile', '');
        $smsCode = $request->post('sms_code', '');
        $token   = $request->header('Authorization', '');

        $res = UserService::getInstance()->bindMobile($this->uid, $mobile, $smsCode, $token);

        if ($res['code'] != 200) return $this->apiFailed($res['msg']);
        return $this->apiSuccess($res['data']);
    }

    /**
     * 解除手机号
     *
     * @param Request $request
     * @return Response
     */
    public function relieveMobile(Request $request): Response
    {
        $validate = new RelieveMobileValidate();
        if (!$validate->check($request->post())) return $this->apiFailed($validate->getError());

        $mobile  = $request->post('mobile', '');
        $smsCode = $request->post('sms_code', '');

        $res = UserService::getInstance()->relieveMobile($this->uid, $mobile, $smsCode);

        if ($res['code'] != 200) return $this->apiFailed($res['msg']);
        return $this->apiSuccess();
    }

    /**
     * 苹果订单支付结果查询
     * /v1/user/payOrderQueryByApple
     *
     * @param Request $request
     * @return Response
     */
    public function payOrderQueryByApple(Request $request): Response
    {
        $validate = new PayOrderQueryByAppleValidate();
        if (!$validate->check($request->post())) return $this->apiFailed($validate->getError());

        $orderNo               = $request->post('order_no', '');
        $orderNo               = getFilterStr($orderNo);
        $receiptData           = $request->post('receipt_data', '');
        $sandbox               = $request->post('sandbox', '');
        $productId             = $request->post('product_id', '');
        $transactionId         = $request->post('transaction_id', '');
        $originalTransactionId = $request->post('original_transaction_id', '');
        $disposableGoods       = $request->post('disposable_goods', '');
        $uid                   = request()->uid;

        $res = PayModelService::instance()->payOrderQueryBastByApple((int)$uid, (string)$orderNo, (string)$receiptData, (int)$sandbox, (string)$productId, (int)$transactionId, (int)$originalTransactionId, (int)$disposableGoods);

        return ($res['code'] == 200) ? $this->apiSuccess(['pay_status' => 1]) : $this->apiFailed($res['msg']);
    }

    /**
     * 苹果票据查询
     * /v1/user/queryBillsByApple
     *
     * @param Request $request
     * @return Response
     */
    public function queryBillsByApple(Request $request): Response
    {
        $validate = new QueryBillsByAppleValidate();
        if (!$validate->check($request->post())) return $this->apiFailed($validate->getError());

        $receiptData = $request->post('receipt_data', '');
        $sandbox     = $request->post('sandbox', '');

        $query = AppleService::instance()->validateApplePay($receiptData, $sandbox);

        return $this->apiSuccess($query);
    }


    /**
     * 苹果恢复购买
     * /v1/user/resumePurchaseByApple
     *
     * @param Request $request
     * @return Response
     */
    public function resumePurchaseByApple(Request $request): Response
    {
        $validate = new ResumePurchaseByAppleValidate();
        if (!$validate->check($request->post())) return $this->apiFailed($validate->getError());

        $originalTransactionId = $request->post('original_transaction_id', '');

        $res = PayModelService::instance()->resumePurchaseByApple($originalTransactionId, request()->uid);

        return ($res['code'] == 200) ? $this->apiSuccess() : $this->apiFailed($res['msg']);
    }
}